import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:getx_learn/app/routes/app_pages.dart';
import 'package:uni_links2/uni_links.dart';

class IndexController extends GetxController {
  //TODO: Implement IndexController

  /// scheme 内部打开
  bool isInitialUriIsHandled = false;
  StreamSubscription? uriSub;

  @override
  void onInit() {
    super.onInit();

    handleInitialUri();
    handleIncomingLinks();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    uriSub?.cancel();
    super.onClose();
  }

  // 第一次打开
  Future<void> handleInitialUri() async {
    if (!isInitialUriIsHandled) {
      isInitialUriIsHandled = true;
      try {
        final uri = await getInitialUri();
        if (uri == null) {
          print('no initial uri');
        } else {
          // 这里获取了 scheme 请求
          print('got initial uri: $uri ${uri.path}');
          jumpTargetPage(uri);
        }
      } on PlatformException {
        print('falied to get initial uri');
      } on FormatException catch (err) {
        print('malformed initial uri, ' + err.toString());
      }
    }
  }

  // 程序打开时介入
  void handleIncomingLinks() {
    if (!kIsWeb) {
      uriSub = uriLinkStream.listen((Uri? uri) {
        // 这里获取了 scheme 请求
        print('got uri: $uri');
        jumpTargetPage(uri);
      }, onError: (Object err) {
        print('got err: $err');
      });
    }
  }

  // 十分已经跳转
  var _isJumped = false;

  /**
   * 跳转目标页面
   */
  void jumpTargetPage(Uri? uri) {
    if (uri != null && uri.path == '/utils') {
      if(_isJumped){
        return;
      }
      _isJumped = true;
      Get.toNamed(Routes.GET_UTILS_DEMO);
    }
  }
}
